package com.nftturbocollection.domain.service.impl.es;

import com.nftturbobase.response.PageResponse;
import com.nftturbocollection.domain.entity.Collection;
import com.nftturbocollection.domain.service.impl.BaseCollectionService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.elasticsearch.core.ElasticsearchOperations;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.query.Criteria;
import org.springframework.data.elasticsearch.core.query.CriteriaQuery;
import org.springframework.data.elasticsearch.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@ConditionalOnProperty(name = "spring.elasticsearch.enable", havingValue = "true")
public class CollectionEsService extends BaseCollectionService {
    @Autowired
    private ElasticsearchOperations  elasticsearchOperations;

    @Override
    public PageResponse<Collection> pageQueryByState(String name, String state, int currentPage, int pageSize) {
        Criteria criteria = null;

        if (StringUtils.isNotBlank(name)) {
            criteria =
                    new Criteria("name")
                            .matches(name)
                            .and(
                                    new  Criteria("state").is(state),
                                    new  Criteria("deleted").is("0")
                            );
        } else {
            criteria =
                    new Criteria("state").is(state)
                    .and(new  Criteria("deleted").is("0"));
        }

        PageRequest pageRequest = PageRequest.of(currentPage - 1, pageSize);
        Query query = new CriteriaQuery(criteria).setPageable(pageRequest).addSort(Sort.by(Sort.Order.asc("create_time")));

        SearchHits<Collection> searchHits = elasticsearchOperations.search(query, Collection.class);
        List<Collection> searchList = searchHits.getSearchHits().stream().map(SearchHit::getContent).toList();
        return PageResponse.of(searchList, (int) searchHits.getTotalHits(), pageSize, currentPage);
    }
}
